<!DOCTYPE html>
<body>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script>
test(drawSRGBThenGetImageDataP3,
    'tests drawing SRGB color on P3 canvas and getting image data in P3.');
test(putImageDataP3ThenGetImageDataP3,
    'tests putting and getting P3 image data on P3 canvas.');
test(putImageDataSRGBThenGetImageDataP3,
    'tests putting SRGB image data on P3 canvas and getting P3 image data.');

function assert_array_approx_equals(actual, expected, epsilon)
{
  assert_true(actual.length === expected.length);
  for (var i=0; i < actual.length; i++)
    assert_approx_equals(actual[i], expected[i], epsilon);
}

function drawSRGBThenGetImageDataP3() {
    var canvas = document.createElement('canvas');
    canvas.width = 10;
    canvas.height = 10;
    var ctx = canvas.getContext('2d',
        {colorSpace: 'display-p3', pixelFormat:'float16'});
    ctx.fillStyle = 'rgb(50, 100, 150)';
    ctx.fillRect(0, 0, 10, 10);
    var pixel = ctx.getImageData(5, 5, 1, 1,
        {colorSpace: 'display-p3', storageFormat:'float32'}).data;
    // Check against the same color in P3. 0.01 protects the test against
    // color conversion deviations.
    assert_array_approx_equals(pixel, [0.24304, 0.38818, 0.57227, 1], 0.01);
}

function putImageDataP3ThenGetImageDataP3() {
    var canvas = document.createElement('canvas');
    canvas.width = 10;
    canvas.height = 10;
    var ctx = canvas.getContext('2d',
        {colorSpace: 'display-p3', pixelFormat:'float16'})
    var dataP3 = new Float32Array(4);
    var imageData = ctx.createImageData(1, 1,
        {colorSpace: 'display-p3', storageFormat:'float32'});
    imageData.data[0] = 0.24304;
    imageData.data[1] = 0.38818;
    imageData.data[2] = 0.57227;
    imageData.data[3] = 1;
    ctx.putImageData(imageData, 5, 5);
    var pixel = ctx.getImageData(5, 5, 1, 1,
        {colorSpace: 'display-p3', storageFormat:'float32'}).data;
    // Check against the same color in P3. 0.001 protects the test against
    // rounding errors.
    assert_array_approx_equals(pixel, [0.24304, 0.38818, 0.57227, 1], 0.001);
}

function putImageDataSRGBThenGetImageDataP3() {
    var canvas = document.createElement('canvas');
    canvas.width = 10;
    canvas.height = 10;
    var ctx = canvas.getContext('2d',
        {colorSpace: 'display-p3', pixelFormat:'float16'});
    var imageData = ctx.createImageData(1, 1,
        {colorSpace: 'srgb', storageFormat:'uint8'});
    imageData.data[0] = 50;
    imageData.data[1] = 100;
    imageData.data[2] = 150;
    imageData.data[3] = 255;
    ctx.putImageData(imageData, 5, 5);
    var pixel = ctx.getImageData(5, 5, 1, 1,
        {colorSpace: 'display-p3', storageFormat:'float32'}).data;
    // Check against the same color in P3. 0.01 protects the test against
    // color conversion deviations.
    assert_array_approx_equals(pixel, [0.24304, 0.38818, 0.57227, 1], 0.01);
}
</script>
</body>
